global dir_size

%define   SIZE_dir_entry          824
%define   SIZE_file_entry         32

%define   OFF_entry_type           0
%define   OFF_name                 4

%define   OFF_DIR_entrys          16
%define   OFF_DIR_others_entrys  816

%define   OFF_FILE_attr           16
%define   OFF_FILE_size           20
%define   OFF_FILE_data           24

%define   TYPE_FILE 0
%define   TYPE_DIR  1

%define   NULL 0

%define TABLE_SIZE 100

section .text

; size_t dir_size(dir_entry *dir)

dir_size:
	push rbx
	push r12
	push r13

	xor  rbx, rbx
	mov  r12,rdi
	cmp  r12, NULL
	je   .end

	mov  rdx, [r12 + OFF_entry_type]
	cmp  byte dl, TYPE_FILE
	je   .isfile

	.loop:
		mov r13, 0
		.tableloop:
			mov   rdi, [r12 + OFF_DIR_entrys + r13*8]
			call  dir_size
			add   ebx, eax
			inc   r13
			cmp   r13, TABLE_SIZE
		jne .tableloop

		mov  r12, [r12 + OFF_DIR_others_entrys]
		cmp  r12, NULL
	jne .loop

	jmp .end

	.isfile:
		mov ebx, [r12 + OFF_FILE_size]
	.end:

	mov eax, ebx
	pop r13
	pop r12
	pop rbx
	ret
